package com.kws.system.util;

import cn.hutool.core.collection.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

/**
 * <b>SendMailUtil</b>
 *
 * @description: SendMailUtil <br>
 * @date: 2024/12/3 16:14 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Component
public class SendMailUtil {
    private static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class);

//    @Value("${email.username}")
    public static String username = "test@kwhos.com";

//    @Value("${email.password}")
    public static String password = "Qq163163@";

    public static void sendMail(String title,String sendMessage, String sendMailNumber){
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "false");
        props.put("mail.smtp.host", "smtphz.qiye.163.com");
        props.put("mail.smtp.port", "25");

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username)); // 设置发件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendMailNumber)); // 设置收件人
            message.setSubject(title); // 设置邮件主题
            message.setText(sendMessage);
            message.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("发送邮件标题"+title+"Email sent successfully");
        } catch (MessagingException e) {
            throw new RuntimeException("Error sending email", e);
        }
    }
}
